<?php
use \Illuminate\Support\Facades\DB;
// 计算合计费用 = 材料单价 * 数量
function sumMaterialPurchasePrice($data = [])
{
	
	foreach ($data as $k => $v) {
		static $total_price = 0;
		$total_price += $v['number'] * $v['unit_price'] * 100;
	}
	
	return $total_price / 100;
}

function get_supplierno()
{
	$a = range(0, 9);
	
	for ($i = 0; $i < 16; $i++) {
		$b[] = array_rand($a);
	}
	
	return join("", $b);
}

//    补全丢失的数据
function fixMonth($x, $param = [])
{
	$data = [];
	foreach ($x as $key => $val) {
		$data[$key] = [
			'x' => $val,
			'value' => 0
		];

		foreach ($param as $item => $value) {
			if ($val == $value['x']) {
				$data[$key] = $value;
			}
		}
	}
	
	return $data;
}

// 计算chart统计表x轴
function countX($count)
{
	$data = [];
	for ($i = 0; $i < $count; $i++) {
		$data[$i] = $i + 1;
	}
	
	return $data;
}

// 判断材料是否被修改过
function checkMaterialIfModified($model, $input)
{
	if(count($model)){
				// 判断是否删除了材料
				if(count($input) != count($model)){
					return false;
					//dd('材料数量不对');
				}
				// 判断是否修改了材料
				foreach ($model as $k => $v) {
					//dd($v->material_id, (int)$input[$v['id']]['material_id'], $v->number,
					//(int)$input[$v['id']]['number']
					//);
					$id  = $v->material_id == (int)$input[$v['id']]['material_id'];
					$number = $v->number == (int)$input[$v['id']]['number'];
					$flag = $id || $number;
					//dd($id || $number, $id, $number);
					if (!$flag) {
						return false;
						//dd('材料被修改了');
					}
				}
				return true;
			};
}

/**
     * 库存扣减算法
     * @return string
     */
function deduction_stock(array $stock, int $need)
    {
        $minimun=[];
        if(is_array($stock) && is_int($need)){
            foreach ($stock as $key => $value){
                $minimun[$key]=$value;
                if($value['status'] == 1){
                    if((int)$value['stock'] >= (int)$need){
                        $minimun[$key]['stock']=(int)$value['stock'] - (int)$need;
                        $minimun[$key]['sell']=(int)$value['sell'] + (int)$need;
                        if((int)$value['stock'] == (int)$need){
                            $minimun[$key]['status']=2;
                        }
                        break;
                    }else{
                        $minimun[$key]['stock']=0;
                        $minimun[$key]['sell']=(int)$value['sell'] + (int)$value['stock'];
                        $minimun[$key]['status']=2;
                        $need=(int)$need-(int)$value['stock'];
                        continue;
                    }
                }
            }
        }
        return $minimun;
    }
// 合计仓库明细
function sumPurchase($data = [])
{
	$price = 0;
	foreach ($data as $v) {
		$price += $v['value'];
	}
	
	return $price;
}

function countHour()
{
	$data = [];
	for ($i = 0; $i<24; $i++){
		$data[] = $i;
	}
	
	return $data;
}

function recordOrderChart($collection)
{
	$count = count($collection);
	
	if ($count) {
		foreach ($collection as $k => $v){
			$collection[$k]['金额'] = $v['金额'] / 100;
		}
	}
	return $collection;
}

function checkIniPriceRes($res)
{
	foreach ($res as $k => $v) {
		if($v !== true){
			return $v;
		}
	}
	
	return true;
}
/**
 *  随机生成代码
 * @param array $data 返回数据
 */
function get_string($length, $type = 1)
{
    switch ($type) {
        case 1:
            $chars = '0123456789';
            break;
        case 2:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            break;
        case 3:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqistuvwxyz0123456789';
            break;
        case 4:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqistuvwxyz0123456789+-=[]{}|\/<> !@#$%^&*:?.,';
            break;
    }
    $return = '';
    for ($i = 0; $i < $length; $i++) {
        $return .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $return;
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 */
function time_format($time = NULL, $format = 'Y-m-d H:i')
{
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 随机生成订单号
 * @return [type] [返回值是一维数组]
 */
function get_number_chang($model, $key)
{
    $string = get_string(6);
    $orderid = time_format(time(), 'Ymd') . $string;
    $where[] = [$key, '=', $orderid];
    $thunk = \Illuminate\Support\Facades\DB::table($model)->where($where)->value($key);
    if ($thunk) {
        get_number_chang($model);
    } else {
        return $orderid;
    }
}

    // 批量更新
    function updateBatch($tableName = "", $multipleData = array())
    {
        if( $tableName && !empty($multipleData) ) {
 
            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id
            unset($updateColumn[0]);
            $whereIn = "";
 
            $q = "UPDATE ".$tableName." SET ";
            foreach ( $updateColumn as $uColumn ) {
                $q .=  $uColumn." = CASE ";
 
                foreach( $multipleData as $data ) {
                    $q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";
                }
                $q .= "ELSE ".$uColumn." END, ";
            }
            foreach( $multipleData as $data ) {
                $whereIn .= "'".$data[$referenceColumn]."', ";
            }
            $q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (".  rtrim($whereIn, ', ').")";
 
            // Update
            return DB::update(DB::raw($q));
 
        } else {
            return false;
        }
 
    }
    
    function json($status = 200, $code = 1, $msg = '', $data = [])
    {
        return response([
        	'status' => $status,
	        'code' => $code,
	        'msg' => $msg,
	        'data' => $data
        ]);
    }